package com.xxwu.messagequeue.demo;

import com.xxwu.messagequeue.common.MqException;
import com.xxwu.messagequeue.mqclient.Channel;
import com.xxwu.messagequeue.mqclient.Connection;
import com.xxwu.messagequeue.mqclient.ConnectionFactory;
import com.xxwu.messagequeue.mqserver.core.BasicProperties;
import com.xxwu.messagequeue.mqserver.core.ExchangeType;

import java.io.IOException;

public class Consumer {
    public static void main(String[] args) throws IOException, MqException, InterruptedException {
        // 创建客户端
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(9090);
        Connection connection = factory.createConnection();

        Channel channel = connection.createChannel();
        channel.createChannel();

        // 消费消息
        channel.exchangeDeclare("demoExchange", ExchangeType.Direct, true, false, null);
        channel.queueDeclare("demoQueue", true, false, false, null);
        channel.basicConsumer(channel.getChannelId(), "demoQueue", true,
                new com.xxwu.messagequeue.common.Consumer() {
                    @Override
                    public void handleDelivery(String consumerTag, BasicProperties properties, byte[] body) throws IOException, MqException {
                        System.out.println("开始消费消息");
                        System.out.println("comsumerTag:" + consumerTag);
                        String payload = new String(body);
                        System.out.println("payload:" + payload);
                        System.out.println("结束消费消息");
                    }
                });
        // 循环等待生产者不断地生产消息
        while (true) {
            Thread.sleep(1000);
        }
        // 最后在主类中将服务器也启动
    }
}
